package common;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.Channel;
import proxy.IProxyFactory;
import rpc.sync.IRpcService;
import rpc.sync.RpcClassRef;
import serialization.ISerialize;

public class ServerChannel extends NetChannel implements IRpcService{

	private Map<Class<?>, RpcClassRef<?>> rpcClassMap = new ConcurrentHashMap<>();
	
	private IProxyFactory proxyFactory;
	
	private ISerialize serialize;
	
	public ServerChannel(Channel channel,IProxyFactory proxyFactory,ISerialize serialize) {
		super(channel);
		this.proxyFactory = proxyFactory;
		this.serialize = serialize;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T rpcService(Class<T> cls)
	{
		RpcClassRef<?> rf = rpcClassMap.get(cls);
		if(rf==null)
		{
			rf  =new RpcClassRef<>(this, proxyFactory, serialize);
			rpcClassMap.putIfAbsent(cls, rf);
		}
		return (T) rf.getRef();
	}
}
